import type { DependencyContainer } from "tsyringe";
import busboy, { FileInfo } from 'busboy'
import { ROOT, Request } from "@sker/core";
import { dirname, join } from "path";
import { createWriteStream, ensureDir } from "fs-extra";

declare const injector: DependencyContainer;
export function useS3Upload(){
    
}
export function useUpload(generateFilename: (info: FileInfo) => string) {
    const req = injector.resolve(Request)
    const root = injector.resolve(ROOT)
    const bb = busboy({ headers: req.headers })
    return new Promise<string>((resolve, reject) => {
        let saveTo: string | null = null;
        let url = ``
        bb.on('file', async (name, file, info) => {
            try {
                url = `/${generateFilename(info)}`
                saveTo = join(root, 'attachments', url);
                await ensureDir(dirname(saveTo))
                file.pipe(createWriteStream(saveTo));
            } catch (e) {
                reject(e)
            }
        })
        bb.on('error', err => reject(err))
        bb.on('close', () => resolve(url))
        bb.on('finish', () => resolve(url))
        req.pipe(bb)
    })
}
